﻿using System;
using Irony.Ast;
using Irony.Parsing;
using LibraryGuard.Interfaces;

namespace LibraryGuard.Internals.AST
{
	/// <summary>
	/// Represents condition expression($[()]).
	/// </summary>
	internal class ConditionExpression
		: IValue
	{
		#region Fields
		private readonly Condition Condition = null;
		private readonly Code Code = null;
		#endregion

		#region Constructors
		public ConditionExpression(Condition cond, Code code)
		{
			this.Condition = cond;
			this.Code = code;
		}
		#endregion

		#region IValue Members
		/// <inheritdoc />
		public TypeCode GetBaseType(IDataProvider data)
		{
			return TypeCode.String;
		}

		/// <inheritdoc />
		public bool CanBeConvertedTo(TypeCode type, IDataProvider data)
		{
			return type == TypeCode.String;
		}

		/// <inheritdoc />
		public object GetValue(TypeCode type, IDataProvider data)
		{
			if (this.Condition.GetResult(data))
				return this.Code.GetValue(TypeCode.String, data);
			return string.Empty;
		}
		#endregion

		#region Statics
		public static void Create(AstContext context, ParseTreeNode parseNode)
		{
			parseNode.AstNode = new ConditionExpression((Condition)parseNode.ChildNodes[0].AstNode, (Code)parseNode.ChildNodes[1].AstNode);
		}
		#endregion
	}
}
